import Common from './common';
import {addTempleteQueCon, COMMON, toastMsg} from "../main/util";
import {saveValidate} from "../../../public/functions/unit";

export default class BatchAddAction extends Common {

    constructor(comp) {
        super();
        this.comp = comp;
    }

    historyState = null;

    // 给批量新增弹窗的查询弹窗添加查询信息
    addQueryConditionToMultiAddSearch = (template) => {
        const {props} = this.comp;
        const {transfer} = props;

        template[COMMON.searchId2].items.map((item) => {
            if (item.attrcode === 'hi_psnjob.clerkcode') {
                item.queryCondition = {
                    pk_org: transfer.hrorgobj.refpk,
                    isIncludeKeyPsnGrp: false,
                    transMode: transfer.stapplyMode,
                    GridRefActionExt: 'nccloud.web.hryf.pub.sqlbuilder.BatchAddClerkcodeRefSqlBuilder',
                    optype: 3
                };
            }
        });
    }

    // 打开批量新增的查询台窗
    openBatchAddSearchModal = () => {
        const {props} = this.comp;
        const {search, meta} = props;
        let template = meta.getMeta();

        this.addQueryConditionToMultiAddSearch(template);

        search.openAdvSearch(COMMON.searchId2, true);
    }

    // 打开批量新增弹窗
    openBatchModal = () => {
        this.batchAdd();
    };

    /**
     * 批量新增
     * @returns {Promise<void>}
     */
    batchAdd = async () => {
        const {props} = this.comp;
        const {transfer, dispatch} = props;
        // 新增前检测调配方式/调配业务类型
        if (!this.addCheck(transfer)) return;
        let postData = {
            pk_org: transfer.hrorgobj.refpk,
            transMode: transfer.stapplyMode,
            transType: transfer.trnsType.refpk
        };
        let res = await dispatch({
            type: 'transfer/batchAdd',
            payload: {
                postData: postData
            }
        });
        if (!res.success) return;
        // 显示批量新增
        dispatch({
            type: 'transfer/update',
            payload: {
                batchAddShow: true
            }
        });
    }

    /**
     * 新增前检测调配方式/调配业务类型
     * @param transfer
     * @returns {boolean} false：不通过   true： 通过
     */
    addCheck = (transfer) => {
        if (!transfer.stapplyMode) {
            this.toast({
                color: 'warning',
                content: transfer.language['gx6008-000244'] //'请选择掉配方式!'
            });
            return false
        }
        if (!transfer.trnsType) {
            this.toast({
                color: 'warning',
                content: transfer.language['gx6008-000245'] //'请选择掉配业务类型!'
            });
            return false
        }
        return true
    }

    // 关闭批量新增弹窗
    closeBatchModal = () => {
        const {props} = this.comp;
        const {transfer,meta} = props;
        let template = meta.getMeta();
        template.pageid = transfer.templateIdObj.template;
        meta.setMeta(template);
        this.comp.props.dispatch({
            type: 'transfer/update',
            payload: {
                batchAddShow: false,
                batchAddCurrentStep: 0
            }
        });
    };

    // 为了解决查询不能是async的问题
    toSearchWrapper = () => {
        this.toSearch();
    };

    // 批量新增弹窗第一步条件选择查询弹窗点击确认
    toSearch = async () => {
        const {props} = this.comp;
        const {dispatch, transfer, editTable, search} = props;

        let postData = {
            ...search.getQueryInfo(COMMON.searchId2, true),
            listpks: this.getExistPks(),
            pk_org: transfer.hrorgobj.refpk,
            transMode: transfer.stapplyMode
        };

        try {
            let res = await dispatch({
                type: 'transfer/conditionSelPsn',
                payload: {
                    postData: postData
                }
            });
            if (!res.success) return;
            if (!res.data) return;
            if (res.data.confirmMsg) {
                this.toast({
                    color: 'warning',
                    content: res.data.confirmMsg
                });
            }
            let tableId = COMMON.addBranch;
            if ((!res.data[tableId]) || (!res.data[tableId][tableId])) return;
            editTable.setTableData(tableId, res.data[tableId][tableId]);
        } catch (e) {
            console.error(e)
        }
    };

    // 获取已存在的listpks
    getExistPks = () => {
        const {props} = this.comp;
        const {dispatch, transfer, editTable} = props;

        let tableData = editTable.getAllRows(COMMON.addBranch);

        let listpks = tableData.map((item) => {
            return item.values['pk_psnjob'].value;
        });

        return listpks
    };

    // 批量新增弹窗第一步参照选择逻辑
    changePersonRefer = async (value) => {
        const {props} = this.comp;
        const {dispatch, transfer, editTable} = props;

        let postData = {
            listpks: this.getExistPks(),
            pk_org: transfer.hrorgobj.refpk,
            refpks: ''
        };

        let refpks = value.map((item) => {
            return item.refpk;
        });
        postData['refpks'] = refpks;

        try {
            let res = await dispatch({
                type: 'transfer/batchAddSelPsnAction',
                payload: {
                    postData: postData
                }
            });
            if (!res.success || !res.data) return;
            if (res.data.confirmMsg) {
                this.toast({
                    color: 'warning',
                    content: res.data.confirmMsg
                });
            }
            let tableId = COMMON.addBranch;
            if (res.data[tableId][tableId]) {
                editTable.setTableData(tableId, res.data[tableId][tableId]);
            }
        } catch (e) {
        }
    };

    // 获取并存储选择的行
    getSelectedRows = () => {
        const {props, state} = this.comp;
        const {transfer, dispatch, editTable} = props;

        let selectedRows = [];

        if (state.selectAll) {
            selectedRows = editTable.getAllRows(COMMON.addBranch);
        } else {
            selectedRows = editTable.getCheckedRows(COMMON.addBranch).map((item) => {
                return item.data
            });
        }

        this.comp.setState({
            selectRows: this.deepCopy(selectedRows)
        });

        return selectedRows;
    };

    // 批量添加弹窗点击下一步
    goToNextStep = async () => {
        const {props} = this.comp;
        const {transfer, dispatch, editTable, form, meta} = props;

        this.historyState = this.deepCopy(editTable.getAllRows(COMMON.addBranch));

        let selectRows = this.getSelectedRows();

        if (selectRows && selectRows.length <= 0) {
            this.toast({
                color: 'warning',
                content: transfer.language['gx6008-000289'] //'请选择要调动的人员!'
            });
            return
        }

        let postData = {
            pk_org: transfer.hrorgobj.refpk,
            transMode: transfer.stapplyMode,
            transType: transfer.trnsType.refpk
        };

        try {
            let res = await dispatch({
                type: 'transfer/batchAddNextStepAction',
                payload: {
                    postData: postData
                }
            });
            let template = meta.getMeta();
            let {formData, ...other} = res.data;
            Object.assign(template, other);
            await new Promise(((resolve) => {
                addTempleteQueCon(template);
                template.pageid = transfer.templateIdObj.batch_add;
                meta.setMeta(template, resolve)
            }));
            await dispatch({
                type: 'transfer/update',
                payload: {
                    batchAddCurrentStep: 1,
                    transtypecode: {}
                }
            });

            let formid = COMMON.formId2;
            form.setFormStatus(formid, 'edit');

            props.form.setAllFormValue({
                [formid]: formData[formid]
            });
        } catch (e) {
        }
    };

    // 批量添加弹窗点击上一步
    goToPrevStep = () => {
        const {props} = this.comp;
        const {transfer, dispatch, editTable} = props;

        dispatch({
            type: 'transfer/update',
            payload: {
                batchAddCurrentStep: 0,
                transtypecode: {}
            }
        });

        if (this.historyState) {
            editTable.setTableData(COMMON.addBranch, {rows: this.historyState}, false);
            this.historyState = null;
        }
    };

    // 当表格选择全部的时候
    selectedAll = (...args) => {
        this.comp.setState({
            selectAll: args[2]
        });
    };

    // 第二步表单编辑前
    formBeforeEdit = async (fprops, moduleId, key, value, data) => {
        const {props, state} = this.comp;
        const {transfer, dispatch, meta} = props;

        let postData = {
            key: key,
            pk_org: transfer.hrorgobj.refpk
        };

        try {
            let res = await dispatch({
                type: 'transfer/batchAddModalFormEditBefore',
                payload: {
                    postData: postData
                }
            });
            if (res.success) {
                let template = meta.getMeta();
                let formArr = this.deepCopy(template.formrelation[COMMON.formId2]);
                formArr.push(COMMON.formId2);
                if (res.data && res.data.refParam) {
                    formArr.map(formId => {
                        template[formId].items.map((item) => {
                            if (item.attrcode === key) {
                                if (!item.queryCondition) item.queryCondition = {};
                                Object.assign(item.queryCondition, res.data.refParam);
                            }
                        });
                    })
                }
                await new Promise((resolve) => {
                    meta.setMeta(template, resolve);
                });
            }
        } catch (e) {

        }
        return true;
    };

    // 批量新增弹窗第二步编辑后
    formAfterEdit = async (fprops, moduleId, key, value, data) => {
        const {props, state} = this.comp;
        const {transfer, dispatch, meta, form} = props;
        let formId = COMMON.formId2;
        let postData = {
            key: key,
            model: form.getAllFormValue(formId),
            pk_org: transfer.hrorgobj.refpk
        };

        try {
            let res = await dispatch({
                type: 'transfer/batchAddModalFormEditAfter',
                payload: {
                    postData: postData
                }
            });

            if (res.success) {
                form.setAllFormValue({
                    [formId]: res.data[formId]
                });
            }
        } catch (e) {
        }
    };

    // 批量新增弹窗点击完成
    submitBatchAdd = async () => {
        const {props, state} = this.comp;
        const {transfer, dispatch, meta, form} = props;
        // 表单验证
        // if (!form.isCheckNow(COMMON.formId2)) return;
        let postData = {
            listpks: [],
            formData: form.getAllFormValue(COMMON.formId2),
            pk_org: transfer.hrorgobj.refpk,
            transMode: transfer.stapplyMode,
            transType: transfer.trnsType.refpk
        };

        postData['listpks'] = state.selectRows.map((item) => {
            return item.values['pk_psnjob'].value
        });
        postData['formData'].rows[0].values.transtype = transfer.transtypecode
        // if (!form.isCheckNow(COMMON.formId)) return;
        let checkFlag = await this.batchAddSaveCheckAction(postData);
        if (!checkFlag) return;
        let bodys_code = ["psninfo_batch","newinfo_batch","newinfo_org_batch","contract_mng_org_batch","exeinfo_batch","endinfo_batch"];
        saveValidate(props, COMMON.formId2, COMMON.formId2, bodys_code, 'extcard',null,transfer.templateIdObj.batch_add).then(async ()=>{
            try {
                let res = await dispatch({
                    type: 'transfer/batchAddSaveAction',
                    payload: {
                        postData: postData
                    }
                });

                if (res.success) {
                    this.toast({
                        color: 'success',
                        content: transfer.language['gx6008-000066'] // 新增成功
                    });
                    this.closeBatchModal();
                    this.pubSub.publish('getMainTableData');
                }
            } catch (e) {
                console.error(e)
            }
        })
    };

    /**
     * 批增保存前校验
     * @param postData
     * @returns {Promise<boolean>}
     */
    batchAddSaveCheckAction = async (postData) => {
        const {transfer, dispatch} = this.comp.props;
        try {
            let res = await dispatch({
                type: 'transfer/batchAddSaveCheckAction',
                payload: {
                    postData: postData
                }
            });

            if (!res.success) {
                return false
            }
            toastMsg(res);
            return true
        } catch (e) {
            console.error(e);
            return false
        }
    }
}
